//
//  MLTestViewController.m
//  LetsParty
//
//  Created by MLin on 15/9/8.
//  Copyright (c) 2015年 MLin. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>
#import "MLPartyListViewController.h"
#import "DZNSegmentedControl.h"
#import "HFTableViewCell.h"
#import "HFViewController.h"
#import "MLParticipantsViewController.h"
#import "HFTopView.h"
#import "CBStoreHouseRefreshControl.h"

static NSString *const kCellIdentify = @"kCellIdentify";
static NSTimeInterval const animationDuration = 0.07;
static NSTimeInterval const indicatorDuration = 0.25; // 网络请求指示器至少出现的时间
static const CGFloat secretCodeTextField_Y = 24;
static const CGFloat secretCodeTextField_Width = 260;
static const CGFloat secretCodeTextField_Height = 35;
static const CGFloat keyButton_Width = secretCodeTextField_Height - 5;
static const CGFloat leftBlank_Width = 10; // 页面左侧的留白
CGFloat partylistSegmentedControl_Height = 30;

@interface MLPartyListViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSMutableArray *_dataSource;
    NSInteger _refreshFlag;
    NSTimer *_timer;
    NSURL *_soundURL;
    SystemSoundID _soundID;
}

@property (nonatomic, strong) UITextField * secretCodeTextField;
@property (nonatomic, strong) UIButton * keyButton;
@property (nonatomic, strong) UIButton * submitButton;
@property (nonatomic, strong) DZNSegmentedControl * partylistSegmentedControl;
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) CBStoreHouseRefreshControl *storeHouseRefreshControl;
@property (nonatomic, strong) GmailLikeLoadingView *loadingView;

@end

@implementation MLPartyListViewController

#pragma mark - initialize
-(void)initPartyListAppearance{
    [self.baseNavigationBar addSubview:self.secretCodeTextField];
    [self.baseNavigationBar addSubview:self.keyButton];
    [self.baseNavigationBar addSubview:self.submitButton];
    [self.view addSubview:self.partylistSegmentedControl];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.loadingView];
    
}

-(void)initDataSource{
    // 活动指示器
    [self.loadingView setHidden:NO];
    [self.loadingView startAnimating];
    __weak typeof(self) myVC = self;
    [CYYNetWorkManager getMyAllParties:^(NSArray *array) {
        _dataSource = [NSMutableArray arrayWithArray:array];
        
        // 请求完数据，隐藏活动指示器
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(indicatorDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [myVC.loadingView stopAnimating];
            [myVC.loadingView setHidden:YES];
            // 刷新数据
            [myVC.tableView reloadData];
        });
        
    } fail:^(NSError *error) {
//        NSLog(@"%@",error);
        
        // 请求完数据，隐藏活动指示器
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(indicatorDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [myVC.loadingView stopAnimating];
            [myVC.loadingView setHidden:YES];
            // 刷新数据
            [myVC.tableView reloadData];
        });
        
    }];
    
}


#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = COLOR_BackgroundGray;
    // 初始化flag为0
    _refreshFlag = 0;
    // 设置NSTimer
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(startKeyAnimation) userInfo:nil repeats:YES];
    [_timer setFireDate:[NSDate distantFuture]];
    // 获得音效文件的全路径
    _soundURL = [[NSBundle mainBundle] URLForResource:@"shake_sound.mp3" withExtension:nil];
    // 加载音效文件，创建音效ID
    _soundID = 0;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)_soundURL, &_soundID);
    
    // 创建界面
    [self initPartyListAppearance];
#pragma mark - 下拉刷新----配置
    self.storeHouseRefreshControl = [CBStoreHouseRefreshControl attachToScrollView:self.tableView target:self refreshAction:@selector(refreshTriggered:) plist:@"storehouse" color:[UIColor grayColor] lineWidth:1.5 dropHeight:80 scale:1 horizontalRandomness:150 reverseLoadingAnimation:YES internalAnimationFactor:0.5];
    
//    NSLOG_CLASSNAME;
//    NSLog(@"当前登录的用户======= %@",[[CYYNetWorkManager currentUserGet] objectForKey:@"name"]);
    
    // 判断用户是否登录，未登录就清空_datasource
    if (![[UserModel defaultUser] isAlreadyLoad]) {
        
        _dataSource = nil;
        // 刷新数据
        [self.tableView reloadData];
        
    } else {
        [self initDataSource];
    }
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
    // 判断用户是否登录，未登录就清空_datasource
    if (![[UserModel defaultUser] isAlreadyLoad]) {
        _dataSource = nil;
        [self.tableView reloadData];
    } else {
        // 刷新数据
        [self refreshSegmentData];
    }
    
}

#pragma mark - action
-(void)startKeyAnimation{
    //进行动画
    [UIView animateWithDuration:1.5 animations:^{
        [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.keyButton cache:YES ];
    } completion:^(BOOL finished) {
        
    }];
}

// 钥匙按钮的点击事件
-(void)respondsToKeyButton{
    // 让暗号输入框进入编辑状态，弹起键盘
    [self.secretCodeTextField becomeFirstResponder];
}

-(void)respondsToSubmitButton{
    [self.submitButton setHidden:YES];
    [self.keyButton setHidden:NO];
    
    // 对输入的暗号进行网络请求以及显示动画效果
    __weak typeof(self) myVC = self;
    [CYYNetWorkManager getPartyObjectIdBySearchPartySecrectCode:self.secretCodeTextField.text sucess:^(BmobObject *party) {
//        NSLOG_CLASSNAME;
//        NSLog(@"对输入的暗号进行网络请求得到party==========%@",party);
        
        // 开始NSTimer调用动画
        [myVC.keyButton setImage:[UIImage imageNamed:@"iconfont-key-4"] forState:UIControlStateNormal];
        [_timer setFireDate:[NSDate distantPast]];
        
        HFViewController *detailVC = [[HFViewController alloc]init];
        
        NSString *partyObjectId = [party objectId];
        // 传入用户对应这个活动的状态
        [CYYNetWorkManager partyStateWithPartyObjectId:partyObjectId sucess:^(NSString *sucessString) {
            detailVC.status = sucessString;
            // 传值给详情界面
            detailVC.partyObjectId = partyObjectId;
            if ([[party objectForKey:@"partySponsorInfo"][@"partySponsorObjectId"]isEqualToString:[[CYYNetWorkManager currentUserGet] objectId]]) {
                detailVC.laucher = @"自己";
            } else {
                detailVC.laucher = [party objectForKey:@"partySponsorInfo"][@"partySponsorName"];
            }
            
            detailVC.partyDetailString = [party objectForKey:@"partyDetailText"];
            detailVC.partyPositionNameString = [party objectForKey:@"partyPositionName"];
            detailVC.partyBeginTimeString = [party objectForKey:@"partyBeginTime"];
            detailVC.partyEndTimeString = [party objectForKey:@"partyEndTime"];
            detailVC.partyTitleString = [party objectForKey:@"partyTitle"];
            detailVC.partySecretCode = [party objectForKey:@"partySecretCode"];
            
            // 传值参加人数
            [CYYNetWorkManager partyParticipatorsNumberWithPartyObjectId:partyObjectId sucess:^(NSInteger partyParticipatorsNumber) {
                
                detailVC.partyParticipatorsNumber = [NSString stringWithFormat:@"%ld",(long)partyParticipatorsNumber];
                
                // 这里结束钥匙的动画
                // 暂停调用NSTimer
                [_timer setFireDate:[NSDate distantFuture]];
                
                // 播放音效
                AudioServicesPlaySystemSound(_soundID);
                
                // 进入详情页
                [myVC.navigationController pushViewController:detailVC animated:YES];
                // 清除暗号输入框输入的文字
                myVC.secretCodeTextField.text = nil;
                [myVC.keyButton setImage:[UIImage imageNamed:@"iconfont-key"] forState:UIControlStateNormal];
                [myVC.secretCodeTextField resignFirstResponder];
                
            } fail:^(NSError *error) {
//                NSLog(@"%@",error);
            }];
            
        } fail:^(NSError *error) {
//            NSLog(@"%@",error);
            
        }];
        
    } fail:^(NSError *error) {
//        NSLOG_CLASSNAME;
//        NSLog(@"%@",error);
        NSString *alertString = [error domain];
        
        if ([alertString isEqualToString:@"查无此活动"]) {
            //进行钥匙抖动动画
            [myVC vibrateAnimationBlock];
        }else{
            //进行钥匙抖动动画
            [myVC vibrateAnimationBlock];
            UIAlertView *alerView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:alertString delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil];
            [alerView show];
        }
    }];
}

// 进入活动详情
-(void)respondsToDetailButton:(UIButton *)sender{
    HFViewController *detailVC = [[HFViewController alloc]init];
    
    HFTableViewCell *clickedcell = (HFTableViewCell *)[[sender superview] superview];
    NSIndexPath *clickedIndexPath = [self.tableView indexPathForCell:clickedcell];
    
    // 传入活动的objecId
    detailVC.partyObjectId = [_dataSource[clickedIndexPath.section] objectId];
    detailVC.laucher = clickedcell.originatorLabel.text;
    
    // 传入传值用的状态
    detailVC.status = clickedcell.undoStatusStr;
    detailVC.partyDetailString = [_dataSource[clickedIndexPath.section] objectForKey:@"partyDetailText"];
    detailVC.partyPositionNameString = [_dataSource[clickedIndexPath.section] objectForKey:@"partyPositionName"];
    detailVC.partyBeginTimeString = [_dataSource[clickedIndexPath.section] objectForKey:@"partyBeginTime"];
    detailVC.partyEndTimeString = [_dataSource[clickedIndexPath.section] objectForKey:@"partyEndTime"];
    detailVC.partyTitleString = [_dataSource[clickedIndexPath.section] objectForKey:@"partyTitle"];
    detailVC.partySecretCode = [_dataSource[clickedIndexPath.section] objectForKey:@"partySecretCode"];
    detailVC.partyParticipatorsNumber = clickedcell.intervenorLabel.text;
    [self.navigationController pushViewController:detailVC animated:YES];
}

// 查看参与者列表
-(void)respondsToAdminButton:(UIButton *)sender{
    MLParticipantsViewController *participantsVC = [[MLParticipantsViewController alloc]init];
    
    // 取到被点击button的cell
    HFTableViewCell *clickedcell = (HFTableViewCell *)[[sender superview] superview];
    // 根据cell取到indexpath，然后就可以从datasource取活动的objectId
    NSIndexPath *clickedIndexPath = [self.tableView indexPathForCell:clickedcell];
    
    // 活动Id和活动标题传值
    participantsVC.partyObjectId = [_dataSource[clickedIndexPath.section] objectId];
    participantsVC.headerTitleStr = [_dataSource[clickedIndexPath.section] objectForKey:@"partyTitle"];
    if ([clickedcell.stateLabel.text isEqualToString:@"已参加"]) {
        participantsVC.isParticipate = YES;
    }else {
        participantsVC.isParticipate = NO;
    }
    // push到参与者列表
    [self.navigationController pushViewController:participantsVC animated:YES];
    
}


-(void)respondsToSegmentedControl:(UISegmentedControl *)sender{
    // 根据目前选中的分类，进行相应的网络请求
    switch (self.partylistSegmentedControl.selectedSegmentIndex) {
        case 0:
        {
            // 我的所有活动
            [self requestMyAllParties];
            if (_refreshFlag) {
                [self finishRefreshControl];
            } else {
                self.tableView.contentOffset = CGPointMake(0, 0);
            }
        }
            break;
        case 1:
        {
            // 我发起的所有活动
            [self requestMyLaunchParties];
            if (_refreshFlag) {
                [self finishRefreshControl];
            } else {
                self.tableView.contentOffset = CGPointMake(0, 0);
            }
        }
            break;
        case 2:
        {
            // 我参加的所有活动
            [self requestMyTakePartyInParties];
            if (_refreshFlag) {
                [self finishRefreshControl];
            } else {
                self.tableView.contentOffset = CGPointMake(0, 0);
            }
        }
            break;
        case 3:
        {
            // 我关注的所有活动
            [self requestMyObserveParties];
            if (_refreshFlag) {
                [self finishRefreshControl];
            } else {
                self.tableView.contentOffset = CGPointMake(0, 0);
            }
        }
            break;
            
        default:
            break;
    }
}

//处理键盘隐藏事件
- (void)respondsToDoneButton{
    [self.view endEditing:YES];
}


-(void)textfieldIsEditing:(UITextField *)textfield{
    if (textfield.text.length > 0) {
        [self.keyButton setHidden:YES];
        [self.submitButton setHidden:NO];
    }else{
        [self.keyButton setHidden:NO];
        [self.submitButton setHidden:YES];
    }
}


#pragma mark - <UITableViewDelegate,UITableViewDataSource>
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return _dataSource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 140 * DHFlexibleVerticalMutiplier();
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 5 * DHFlexibleVerticalMutiplier();
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5 * DHFlexibleVerticalMutiplier();
}

// 取消选中高亮
-(BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

-(HFTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    HFTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify];
    if (!cell) {
        cell = [[HFTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kCellIdentify];
    }
    
    /*   配置cell内容   */
    cell.titleLabel.text = [_dataSource[indexPath.section] objectForKey:@"partyTitle"];
    
    // 拼接开始时间和结束时间
    NSString *halfString = [[_dataSource[indexPath.section] objectForKey:@"partyBeginTime"] stringByAppendingString:@" - "];
    NSString *fullTimeString = [halfString stringByAppendingString:[_dataSource[indexPath.section] objectForKey:@"partyEndTime"]];
    cell.timeLabel.text = fullTimeString;
    cell.addressLabel.text = [_dataSource[indexPath.section] objectForKey:@"partyPositionName"];
    
    // 设置发起人姓名
    NSString *laucherObjectId = [[_dataSource[indexPath.section] objectForKey:@"partySponsor"] objectId];
    [CYYNetWorkManager getUserDetailInfoWithOnjectId:laucherObjectId sucess:^(BmobObject *bUser) {
        if ([[bUser objectForKey:@"name"]isEqualToString:[[CYYNetWorkManager currentUserGet] objectForKey:@"name"]]) {
            cell.originatorLabel.text = @"自己";
//            cell.originatorLabel.textColor = [UIColor orangeColor];
        } else {
            cell.originatorLabel.text = [bUser objectForKey:@"name"];
        }
    } fail:^(NSError *error) {
//        NSLog(@"%@",error);
    }];
    
    // 设置参加人数
    NSString *partyObjectId = [_dataSource[indexPath.section] objectId];
    [CYYNetWorkManager partyParticipatorsNumberWithPartyObjectId:partyObjectId sucess:^(NSInteger partyParticipatorsNumber) {
        cell.intervenorLabel.text = [NSString stringWithFormat:@"%ld",(long)partyParticipatorsNumber];
    } fail:^(NSError *error) {
//        NSLog(@"%@",error);
    }];
    
    // 设置状态
    [CYYNetWorkManager partyStateWithPartyObjectId:partyObjectId sucess:^(NSString *sucessString) {
        
        // 第一个状态用来传值
        cell.undoStatusStr = sucessString;
        
        if ([sucessString isEqualToString:@"已取消"]) {
            // 该cell的所有字变灰色======暂时注释，会有重用机制的问题没解决
//            cell.titleLabel.textColor = [UIColor grayColor];
//            cell.time.textColor = [UIColor grayColor];
//            cell.timeLabel.textColor = [UIColor grayColor];
//            cell.address.textColor = [UIColor grayColor];
//            cell.addressLabel.textColor = [UIColor grayColor];
//            cell.originator.textColor = [UIColor grayColor];
//            cell.originatorLabel.textColor = [UIColor grayColor];
//            cell.admin.textColor = [UIColor grayColor];
//            cell.intervenorLabel.textColor = [UIColor grayColor];
            cell.stateLabel.text = @"已取消";
            cell.stateLabel.backgroundColor = [UIColor darkGrayColor];
            cell.stateLabel.textColor = [UIColor whiteColor];
        } else if ([sucessString isEqualToString:@"已参加"]){
            cell.stateLabel.text = @"已参加";
            cell.stateLabel.backgroundColor = COLOR_TagGreen;
            cell.stateLabel.textColor = [UIColor whiteColor];
        } else if ([sucessString isEqualToString:@"已关注"]){
            cell.stateLabel.text = @"已关注";
            cell.stateLabel.backgroundColor = COLOR_TagBlue;
            cell.stateLabel.textColor = [UIColor whiteColor];
        }
    } fail:^(NSError *error) {
//        NSLog(@"%@",error);
    }];
    
    //  detialButton 活动详情键
    [cell.detialButton addTarget:self action:@selector(respondsToDetailButton:) forControlEvents:UIControlEventTouchUpInside];
    //  adminButton 查看活动参与者键
    [cell.adminButton addTarget:self action:@selector(respondsToAdminButton:) forControlEvents:UIControlEventTouchUpInside];
    // 设置圆角
    cell.backgroundColor = [UIColor clearColor];
    cell.contentView.backgroundColor = [UIColor whiteColor];
    cell.contentView.layer.cornerRadius = 8;
    return cell;
}

#pragma mark - Notifying refresh control of scrolling

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.storeHouseRefreshControl scrollViewDidScroll];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self.storeHouseRefreshControl scrollViewDidEndDragging];
}

#pragma mark - Listening for the user to trigger a refresh
- (void)refreshTriggered:(id)sender
{
    // flag置为1，表示正在进行下拉动画
    _refreshFlag = 1;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        if (![[UserModel defaultUser] isAlreadyLoad]) {
            [self finishRefreshControl];
//            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"当前未登陆账号,但是您可以输入暗号查找活动。" preferredStyle:UIAlertActionStyleDefault];
//            [alert addAction:[UIAlertAction actionWithTitle:<#(NSString *)#> style:<#(UIAlertActionStyle)#> handler:<#^(UIAlertAction *action)handler#>]];
//            [self presentViewController:alert animated:<#(BOOL)#> completion:<#^(void)completion#>];
        } else {
            // 根据目前选中的分类，进行相应的网络请求
            [self refreshSegmentData];
        }
        
    });
    
}

- (void)finishRefreshControl
{
    // 加判断，并恢复flag为0
    if (_refreshFlag == 1) {
        _refreshFlag = 0;
        [self.storeHouseRefreshControl finishingLoading];
    }
    return;
}


#pragma mark - private method

-(void)refreshSegmentData{
    // 根据目前选中的分类，进行相应的网络请求
    switch (self.partylistSegmentedControl.selectedSegmentIndex) {
        case 0:
        {
            // 我的所有活动
            [self requestMyAllParties];
        }
            break;
        case 1:
            // 我发起的所有活动
            [self requestMyLaunchParties];
            break;
        case 2:
            // 我参加的所有活动
            [self requestMyTakePartyInParties];
            break;
        case 3:
            // 我关注的所有活动
            [self requestMyObserveParties];
            break;
            
        default:
            break;
    }
}

-(void)vibrateAnimationBlock{
    [UIView animateWithDuration:animationDuration
                     animations:^{
                         [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
                         [UIView setAnimationRepeatCount:5];                            // 这里设置动画重复次数
                         self.keyButton.center = CGPointMake(self.keyButton.center.x +2, self.keyButton.center.y -1);
                     }
                     completion:^(BOOL finished) {
                         [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
                         [UIView animateWithDuration:animationDuration animations:^{
                             self.keyButton.center = CGPointMake(self.keyButton.center.x -4, self.keyButton.center.y +2);
                         } completion:^(BOOL finished) {
                             [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
                             self.keyButton.center = CGPointMake(self.keyButton.center.x +2, self.keyButton.center.y -1);
                         }];
                     }];
}

// 我的所有活动
-(void)requestMyAllParties{
    
//    // 活动指示器
//    [self.loadingView setHidden:NO];
//    [self.loadingView startAnimating];
    __weak typeof(self) myVC = self;
    [CYYNetWorkManager getMyAllParties:^(NSArray *array) {
        _dataSource = [NSMutableArray arrayWithArray:array];
        
//        // 请求完数据，隐藏活动指示器
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(indicatorDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self.loadingView stopAnimating];
//            [self.loadingView setHidden:YES];
//            // 刷新数据
//            [self.tableView reloadData];
//        });
        
        // 关闭下拉刷新动画并刷新界面
        if (_refreshFlag == 1) {
            [myVC finishRefreshControl];
        }
        [myVC.tableView reloadData];
        
    } fail:^(NSError *error) {
//        NSLog(@"%@",error);
        
        // 关闭下拉刷新动画
        if (_refreshFlag == 1) {
            [myVC finishRefreshControl];
        }
        
        // 请求完数据，隐藏活动指示器
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(indicatorDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self.loadingView stopAnimating];
//            [self.loadingView setHidden:YES];
//            // 刷新数据
//            [self.tableView reloadData];
//        });
        
        
    }];
}

// 我发起的活动
-(void)requestMyLaunchParties{
//    // 活动指示器
//    [self.loadingView setHidden:NO];
//    [self.loadingView startAnimating];
    __weak typeof(self) myVC = self;
    [CYYNetWorkManager getMySponsorPartiesSucessGet:^(NSArray *array) {
        _dataSource = [NSMutableArray arrayWithArray:array];
        
//        // 请求完数据，隐藏活动指示器
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(indicatorDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self.loadingView stopAnimating];
//            [self.loadingView setHidden:YES];
//            // 刷新数据
//            [self.tableView reloadData];
//        });
        
        // 关闭下拉刷新动画并刷新界面
        if (_refreshFlag == 1) {
            [myVC finishRefreshControl];
        }
        [myVC.tableView reloadData];
        
    } fail:^(NSError *error) {
        
//        NSLog(@"%@",error);
        
        // 关闭下拉刷新动画
        if (_refreshFlag == 1) {
            [myVC finishRefreshControl];
        }
        
//        // 请求完数据，隐藏活动指示器
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(indicatorDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self.loadingView stopAnimating];
//            [self.loadingView setHidden:YES];
//            // 刷新数据
//            [self.tableView reloadData];
//        });
        
    }];
}

// 我关注的活动
-(void)requestMyObserveParties{
//    // 活动指示器
//    [self.loadingView setHidden:NO];
//    [self.loadingView startAnimating];
    __weak typeof(self) myVC = self;
    [CYYNetWorkManager getMyObserveParties:^(NSArray *array) {
        _dataSource = [NSMutableArray arrayWithArray:array];
        
//        // 请求完数据，隐藏活动指示器
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(indicatorDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self.loadingView stopAnimating];
//            [self.loadingView setHidden:YES];
//            // 刷新数据
//            [self.tableView reloadData];
//        });
        
        // 关闭下拉刷新动画并刷新界面
        if (_refreshFlag == 1) {
            [myVC finishRefreshControl];
        }
        [myVC.tableView reloadData];
        
    } fail:^(NSError *error) {
//        NSLog(@"%@",error);
        
        // 关闭下拉刷新动画
        if (_refreshFlag == 1) {
            [myVC finishRefreshControl];
        }
        
//        // 请求完数据，隐藏活动指示器
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(indicatorDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self.loadingView stopAnimating];
//            [self.loadingView setHidden:YES];
//            // 刷新数据
//            [self.tableView reloadData];
//        });
    }];
}

// 我参加的活动
-(void)requestMyTakePartyInParties{
//    // 活动指示器
//    [self.loadingView setHidden:NO];
//    [self.loadingView startAnimating];
    __weak typeof(self) myVC = self;
    [CYYNetWorkManager getMyTakePartyInParties:^(NSArray *array) {
        _dataSource = [NSMutableArray arrayWithArray:array];
        
//        // 请求完数据，隐藏活动指示器
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(indicatorDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self.loadingView stopAnimating];
//            [self.loadingView setHidden:YES];
//            // 刷新数据
//            [self.tableView reloadData];
//        });
        
        // 关闭下拉刷新动画并刷新界面
        if (_refreshFlag == 1) {
            [myVC finishRefreshControl];
        }
        [myVC.tableView reloadData];
        
    } fail:^(NSError *error) {
//        NSLog(@"%@",error);
        
        // 关闭下拉刷新动画并刷新界面
        if (_refreshFlag == 1) {
            [myVC finishRefreshControl];
        }
        
//        // 请求完数据，隐藏活动指示器
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(indicatorDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self.loadingView stopAnimating];
//            [self.loadingView setHidden:YES];
//            // 刷新数据
//            [self.tableView reloadData];
//        });
    }];
}

//键盘uitoolbar
- (UIToolbar * )customKeyboardToolbar{
    UIToolbar * toolbar = [[UIToolbar alloc]init];
    toolbar.barTintColor = [UIColor whiteColor];
    toolbar.frame = DHFlexibleFrame(CGRectMake(0, 0, 320, 30), YES);
    //隐藏按钮
    UIBarButtonItem * spaceBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    spaceBarButtonItem.width = 200;
    UIBarButtonItem * secondRightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-bohaojianpanshouqi"] style:UIBarButtonItemStylePlain target:self action:@selector(respondsToDoneButton)];
    secondRightBarButtonItem.tintColor = [UIColor darkGrayColor];
    secondRightBarButtonItem.width = 40;
    toolbar.items = @[spaceBarButtonItem,secondRightBarButtonItem];
    return toolbar;
}

#pragma mark - getter

// 活动指示器视图
-(GmailLikeLoadingView *)loadingView{
    if (!_loadingView) {
        _loadingView = [[GmailLikeLoadingView alloc]initWithFrame:CGRectMake(320*0.5 - 12, 568*0.5 - 12, 15, 15) adjustWidth:YES];
        [_loadingView setHidden:YES];
    }
    return _loadingView;
}

-(UITextField *)secretCodeTextField{
    if (!_secretCodeTextField) {
        _secretCodeTextField = [[UITextField alloc]initWithFrame:CGRectMake(leftBlank_Width, secretCodeTextField_Y, secretCodeTextField_Width, secretCodeTextField_Height) adjustWidth:NO];
        _secretCodeTextField.backgroundColor = COLOR_RGB(231, 231, 235, 1);
        _secretCodeTextField.placeholder = @"请输入暗号";
        _secretCodeTextField.layer.cornerRadius = 5;
        _secretCodeTextField.textAlignment = NSTextAlignmentLeft;
        [_secretCodeTextField setTextColor:COLOR_RGB(56, 60, 60, 1)];
        _secretCodeTextField.font = [UIFont systemFontOfSize:16 * DHFlexibleVerticalMutiplier()];
        _secretCodeTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _secretCodeTextField.keyboardType = UIKeyboardTypeDefault;
        UILabel *textfieldBlankLabel = [[UILabel alloc]initWithFrame:CGRectMake(_secretCodeTextField.frame.origin.x, _secretCodeTextField.frame.origin.y, leftBlank_Width * DHFlexibleHorizontalMutiplier(), _secretCodeTextField.bounds.size.height)];
        _secretCodeTextField.leftView = textfieldBlankLabel;
        _secretCodeTextField.leftViewMode = UITextFieldViewModeAlways;
        _secretCodeTextField.inputAccessoryView = [self customKeyboardToolbar];
        [_secretCodeTextField addTarget:self action:@selector(textfieldIsEditing:) forControlEvents:UIControlEventEditingChanged];
    }
    return _secretCodeTextField;
}

-(UIButton *)keyButton{
    if (!_keyButton) {
        _keyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_keyButton setFrame:CGRectMake(Screen_width - (10 + keyButton_Width)*DHFlexibleHorizontalMutiplier(), (secretCodeTextField_Y + 2) * DHFlexibleVerticalMutiplier(), keyButton_Width * DHFlexibleVerticalMutiplier() , keyButton_Width * DHFlexibleVerticalMutiplier())];
        [_keyButton setImage:[UIImage imageNamed:@"iconfont-key"] forState:UIControlStateNormal];
        [_keyButton setImage:[UIImage imageNamed:@"iconfont-key-high"] forState:UIControlStateHighlighted];
        _keyButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [_keyButton addTarget:self action:@selector(respondsToKeyButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _keyButton;
}

-(UIButton *)submitButton{
    if (!_submitButton) {
        _submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_submitButton setFrame:CGRectMake(CGRectGetMaxX(self.secretCodeTextField.frame) + 5*DHFlexibleHorizontalMutiplier(), (secretCodeTextField_Y + 2) * DHFlexibleVerticalMutiplier(), (keyButton_Width + 7) * DHFlexibleVerticalMutiplier() , (keyButton_Width + 7) * DHFlexibleVerticalMutiplier())];
        [_submitButton setTitle:@"确定" forState:UIControlStateNormal];
        _submitButton.backgroundColor = [UIColor clearColor];
        _submitButton.titleLabel.font = [UIFont boldSystemFontOfSize:15*DHFlexibleVerticalMutiplier()];
        [_submitButton setTitleColor:COLOR_TagBlue forState:UIControlStateNormal];
        _submitButton.hidden = YES;
        [_submitButton addTarget:self action:@selector(respondsToSubmitButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _submitButton;
}

-(DZNSegmentedControl *)partylistSegmentedControl{
    if (!_partylistSegmentedControl) {
        _partylistSegmentedControl = [[DZNSegmentedControl alloc]initWithItems:@[@"所有活动",@"我发起",@"已参加",@"已关注"]];
        // 不显示标题上的当页cell计数
        _partylistSegmentedControl.showsCount = NO;
        [_partylistSegmentedControl setFrame:DHFlexibleFrame(CGRectMake(0, 64, 320, 30), NO)];
        
        // 已在.m文件的方法里面改字体大小
        
        // 把第三方的height属性从readonly改为了readwrite
        _partylistSegmentedControl.height = 30 * DHFlexibleVerticalMutiplier();
        [_partylistSegmentedControl addTarget:self action:@selector(respondsToSegmentedControl:) forControlEvents:UIControlEventValueChanged];
    }
    return _partylistSegmentedControl;
}


-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:DHFlexibleFrame(CGRectMake(10, 64 + 1 +30, 300, 568 - 64 - TABBAR_Height - 30), NO) style:UITableViewStyleGrouped];
        //设置代理
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = COLOR_BackgroundGray;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        self.automaticallyAdjustsScrollViewInsets = NO;
//        self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.01f)];
    }
    return _tableView;
}


@end
